import datetime
import hashlib

import pymongo
from bson import ObjectId

uri = "mysql+pymysql://centros@9730012Cem@101.34.37.253/"
client = pymongo.MongoClient(uri)
db = client['Hao6v']
listcol = db['movie_list']
movieCol = db['movie']
categorCol = db['category']


def save_categories(cate):
    if not categorCol.find_one({'url': cate['url']}):
        categorCol.insert_one(cate)


def get_categories():
    result = []
    cursor = categorCol.find({})
    for c in cursor:
        result.append(dict(c))
    return result

def get_category(cate):
    return categorCol.find_one({'category': cate})

def get_movie(title='', url='', md5='',name='', id=''):
    if name:
        query = {'name':name}
    if title:
        query = {'title': title}
    if url:
        query = {'url': url}
    if md5:
        query = {'md5': md5}
    if id:
        query = {'_id': ObjectId(id)}
    if not md5 and not title and not url and not id:
        return
    return listcol.find_one(query)


def save_movie_list(movies, updateCategory=True):
    total = len(movies)
    savedCount = 0
    for m in movies:
        now = datetime.datetime.now()
        nowStr = now.strftime('%Y-%m-%d %H:%M:%S')
        m.update({
            'title': m['title'],
            'md5': hashlib.md5(m['url'].encode('utf-8')).hexdigest(),
            'updatedAt': nowStr,
        })
        if listcol.count_documents({'$and': [{'md5': m['md5']}, {'title': m['title']}]}):
            print('已保存过的电影', m['title'], m['url'])
            savedCount += 1
            continue
        m['detailed'] = 0
        if not listcol.find_one_and_update({'md5': m['md5'], 'title': {'$ne': m['title']}}, {'$set': m}):
            m.update({'createdAt': nowStr})
            ret = listcol.insert_one(m)
            if ret.acknowledged:
                print('保存成功', m['title'], m['category'])
        else:
            print('更新成功', m['title'], m['category'])
        if listcol.count_documents({'url': m['url']})>1:
            index = 0
            for c in listcol.find({'url': m['url']}).sort([('detailed', pymongo.ASCENDING), ('createdAt', pymongo.DESCENDING)]):
                if index> 0:
                    listcol.delete_one(c)
                index += 1
    return total > savedCount


def get_undetail_movie():
    return listcol.find_one({'$or': [
        {'detailed': 0},
        {'detailed': {'$exists': False}}
    ]}, sort=[('date', pymongo.DESCENDING)])


def get_failed_movie():
    ret = listcol.find_one(
        {'detailed': -1}
    )
    return ret


def delete_movie(m):
    listcol.delete_one(m)


def set_detailed(m, result=1):
    listcol.update_one({'md5': m['md5']}, {'$set': {'detailed': result}})


def del_same_name_movie(m):
    title = m['title']
    name = m['name']
    url = m['url']
    count = movieCol.count_documents({'title': title, 'name': name})
    if count == 1:
        return
    cursor = movieCol.find({'title': title, 'name': name}).sort(
        [('valid', pymongo.DESCENDING), ('updatedAt', pymongo.DESCENDING)])
    index = 0
    for next in cursor:
        if index > 0:
            print('删除重复条目', title, url)
            movieCol.delete_one(next)
        index += 1
    count = movieCol.count_documents({'url': url})
    if count == 1:
        return
    cursor = movieCol.find({'url': url}).sort(
        [('valid', pymongo.DESCENDING), ('updatedAt', pymongo.DESCENDING)])
    index = 0
    for next in cursor:
        if index > 0:
            print('删除重复条目', title, url)
            movieCol.delete_one(next)
        index += 1


def save_movie_detail(m):
    m.update({
        'md5': hashlib.md5(m['url'].encode('utf-8')).hexdigest(),
        'updatedAt': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    })
    if '_id' in m.keys():
        m.pop('_id')
    if movieCol.count_documents({'md5': m['md5']}):
        movieCol.update_one({'md5': m['md5']}, {'$set': m})
        set_detailed(m)
        print('更新已保存', m['title'])
        return
    m['createdAt'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    ret = movieCol.insert_one(m)
    if ret.acknowledged:
        set_detailed(m)
        print('保存成功', m['title'], m['online'], end='\n\n')
        # 查找有没有同名的电影，如果有同名的电影，首先判断当前valid是否为1，如果valid为1，删除早先版本，如果valid
        del_same_name_movie(m)
    else:
        set_detailed(m, -1)
        print('保存失败', m['title'], end='\n\n')


def clear_detail():
    listcol.update_many({}, {'$set': {'detailed': 0}})


def get_invalid_movie():
    return movieCol.find_one({'$and': [
        {'valid': {'$exists': False}},
        {'online': {'$ne': []}}
    ]}, {'md5': 1, 'name': 1, 'online': 1, 'title': 1}, sort=[('date', pymongo.DESCENDING)])


def set_movie_online_verified(movie, verified, valid):
    movieCol.update_one({'md5': movie['md5']}, {'$set': {'online': verified, 'valid': valid}})


def get_movie_for_update_category():
    return movieCol.find_one({'$and':
                                  [{'main_category': {'$exists': False}},
                                   {'category': {'$exists': True}}]
                              }, {'category': 1, 'md5': 1, 'title': 1})


def update_movie_category(movie):
    movieCol.update_one({'md5': movie['md5']}, {'$set': movie})
    print(movie['title'], movie['main_category'], movie['sub_category'])


def get_uncate_movie():
    cursor = movieCol.find({'category': {'$exists': False}}, {'md5': 1, 'title': 1, 'valid': 1})
    ret = []
    for c in cursor:
        ret.append(c)
    return ret


def find_my_category(movie):
    return listcol.find_one({'md5': movie['md5'], 'category': {'$exists': True}}, {'category': 1})


if __name__ == '__main__':
    ret = get_invalid_movie()
    print(ret)
